using Lzfy_His_Service.Models;
using Lzfy_His_Service.Services;
using Senparc.CO2NET;
using Senparc.CO2NET.RegisterServices;
using Senparc.Weixin;
using Senparc.Weixin.Entities;
using Senparc.Weixin.RegisterServices;
using Senparc.Weixin.Work;

namespace Lzfy_His_Service.Extensions
{
    /// <summary>
    /// 企业微信服务扩展
    /// </summary>
    public static class WeChatWorkServiceExtensions
    {
        /// <summary>
        /// 添加企业微信服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configuration">配置</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddWeChatWorkServices(this IServiceCollection services, IConfiguration configuration)
        {
            // 配置企业微信设置
            services.Configure<WeChatWorkConfig>(configuration.GetSection("WeChatWork"));

            // 注册企业微信服务
            services.AddScoped<IWeChatWorkService, WeChatWorkService>();

            // 注册Senparc.Weixin服务
            services.AddSenparcWeixinServices(configuration);
            
            // 注册内存缓存
            services.AddMemoryCache();

            return services;
        }

        /// <summary>
        /// 使用企业微信服务
        /// </summary>
        /// <param name="app">应用构建器</param>
        /// <param name="env">环境</param>
        /// <param name="configuration">配置</param>
        /// <returns>应用构建器</returns>
        public static IApplicationBuilder UseWeChatWorkServices(this IApplicationBuilder app, IWebHostEnvironment env, IConfiguration configuration)
        {
            // 启动 CO2NET 全局注册，必须！
            var senparcSetting = new SenparcSetting() { IsDebug = env.IsDevelopment() };
            var senparcWeixinSetting = new SenparcWeixinSetting() { IsDebug = env.IsDevelopment() };
            IRegisterService register = RegisterService.Start(senparcSetting)
                .UseSenparcGlobal()
                .UseSenparcWeixin(senparcWeixinSetting);

            // 注册企业微信
            var weChatWorkConfig = configuration.GetSection("WeChatWork");
            var corpId = weChatWorkConfig["CorpId"];
            var corpSecret = weChatWorkConfig["CorpSecret"];

            if (!string.IsNullOrEmpty(corpId) && !string.IsNullOrEmpty(corpSecret))
            {
                register.RegisterWorkAccount(corpId, corpSecret, "企业微信登录");
            }

            return app;
        }
    }
}